local desc_xlkj_mode = [[
  # 修罗抗金简介
  ___

  军八4个玩家（身份固定为主忠，玩家不足人机补位）对抗4个阴间人机（身份固定为反贼，体力和体力上限+2）

  胜利条件：反贼全部阵亡。

  失败条件：主忠全部阵亡。

  修罗神礼：每轮开始，每个玩家从3选1选项中选择并执行其效果。

]]
-- local XlkjObj = require "packages/xlkj/XlkjObj"
local U = require "packages/utility/utility"

--开启测试
local IStest = false
--开启测试AI武将
local IStestAI = false
--修罗技能
local getSkillByRoundStart = {}
--将广技能池
local jiangguangSkills = {
  wei={"ex__jianxiong","ex__fankui","ex__ganglie","ex__qingjian","jiushi","ex__tuxi","ex__luoyi","ex__luoshen","xunxun","chengxiang","jianmie",
  "ol_ex__miji","ol_ex__shebian","ol_ex__jushou","ol_ex__jieming","quhu","ol_ex__duanliang","bolong","weikui","lizhan","ol__jingce","benyu",
  "benyu","yawang","gushe","chouce","weijing","ol__wanwei","jixian","saodi","zengou","huanfu","gongjie","tousui"},

  shu={"ex__rende","ex__yijue","ex__guanxing","yajiao","ex__tieji","jianyan","jijie","m_ex__fangquan","m_ex__tiaoxin","ol_ex__liegong","mini__kuanggu",
  "ol_ex__huoji","ol_ex__lianhuan","ol_ex__xuanhuo","zhanding","zhuri","ol__xuehen","ol__sanyao","fengpo","ziyuan","bingzheng","shuimeng","jianji","sigong","dianjun",
  "hongji","tingxian","ty__wuyuan"},

  wu={"ex__zhiheng","fenwei","gongxin","keji","kurou","ex__yingzi","ex__fanjian","ex__guose","ex__qianxun","ex__jieyin","xiaoji","ol_ex__zhiyan","zhijian","ol_ex__guzheng",
  "ol_ex__ganlu","ol_ex__lihuo","ol_ex__zhiyan","bizheng","duwu","jinzhi","ty__meibu","yingjian","anjian"},

  qun={"qingnang","liyu","ol_ex__jianchu","ex__biyue","lijian","ty_ex__qiaomeng","ty__kuangfu","ol_ex__beige","m_ex__luanji","ol_ex__mieji","ol_ex__qieting",
  "ty__fenglue","zhidao","lianzhu","tunjiang","liejie","jianman","kenshang","langdao","shandao","yichengl","hunjiang"},
}
--强将技能池
local qiangjiangSkills = {
  wei={"qingguo","wangxi","ol_ex__renxin","ol_ex__chengxiang","luoying","ol_ex__jiangchi","ol_ex__zhenlie","ol_ex__shensu","ol_ex__jiewei","ol_ex__qiangxi",
  "xieshu","ol__qingxian","ol__caishi","tuifeng","qingzhong","ol__yuejian","zhangjiq","kanpod","gengzhan","qingyix","xiangxu"},

  shu={"ol_ex__kanpo","ol_ex__changbiao","ol_ex__enyuan","ex__longdan","yirong","weilingy","duoshou","ol__huxiao","ol__qirang","ol__yuhua","yuxu",
  "sheyan","juanxia","gue","kangrui","zhenying","yanru","jilis","ty_ex__dangxian","longyin","ty_ex__benxi","ty_ex__zhongyong","ty_ex__xiantu","ty_ex__yanyu","ty_ex__qiaoshi"},

  wu={"ol_ex__tianxiang","ol_ex__fenji","tianyi","ol_ex__wulie","ol_ex__dimeng","ol_ex__jiang","ol_ex__zhijian","ol_ex__buyi","ol__dulie","shenxing","aocai","lixia","dingpan",
  "weiyi","xianbi","cangxin","runwei","ol__fengyan","suji","chanshuang","xiecui","heji"},

  qun={"ol_ex__leiji","ol_ex__shuangxiong","ol_ex__luanwu","ol_ex__zishou","ol_ex__fencheng","anyong",
  "ol__zhuiji","ol__shichou","ol__zhendu","ol__niluan","ol__gaolan","wenji","fuji","gangzhi","neifa","yuanzi","liantao","pingduan","renxia"
  },
}
--玩家将池
local playerGens = {"zhoubuyi","yuanji","ty_ex__huangyueying","ty_ex__lingtong","ty_ex__wangyi","ty_ex__zhuran","ty_ex__wuyi","chenshi","tystar__caoren","ty__yangyi",
"zhoushan","caomao","chentai","olmou__jiangwei","ol__feiyi","caoshuang","luotong","chengjiw","ty__huangzu","ol__huangzu","m_ex__liru","mu__daqiao",
"mu__miheng","mu__xiaoqiao","gongsunxiu","mengyou","gongsundu","ty__zhangmancheng","zhangchu","peiyuanshao","liupi","liangxing","tangji","niufu","dongxie","ty__zhangchangpu",
"fengfang","ty__niujin","ty__mifangfushiren","ty__zhaoyan","wangwei","liyixiejing","sunhuan","ty__mengda","shiyi","ty__guanyu","dufuren","qinyilu","bianxi","ty__huban","ty__hujinding","guannings","ty__nanhualaoxian","ty__tongyuan",
"ty__zhangning","ty__pangdegong","ty_ex__sunluban","ty_ex__zhangsong","ty_ex__caorui","ty_ex__caoxiu","ty_ex__sunxiu","ty_ex__caozhang","ty_ex__xunyou","ty_ex__guohuanghou","ty_ex__taishici","ty_ex__gongsunzan","ty__sunluyu","zhaoyanw","zhangxuan","ty__sunru","xiahoulingnv","pangshanmin","zhanghu","lvlingqi",
"liuyong","wanniangongzhu","panghui","ty__zhaotongzhaoguang","yuantanyuanshangyuanxi","yuechen","ty__jiaxu","ty__chendeng","caimaozhangyun","ty__gaolan","yinfuren","ty__lvkuanglvxiang",
"chengui","chenjiao","qinlang","ty__dongzhao","ty__tangzi","ty__lifeng","xianglang","furongfuqian","ty__huojun","ty__wuban","ty__yanghu","ty__xunchen","ty__miheng","luyusheng","wupu","zhenghun",
"ty__sunhanhua","wanglie","guanning","dongwan","ty__qiaorui","ty__yuejiu","sunchen","ty__sunziliufang","ty__zhujun","ty__dingyuan","ty__wangrongh","ty__caosong","ty__dongcheng","caoanmin",
"yanfuren","ty__zhuling","yanrou","tymou__jvshou","tymou__zhangxiu","tymou__guanping","tymou__caoshuang","tymou__simashi","tymou__lusu","ty__huangfusong","ty__wangjun","simahui","ty__puyuan",
"gexuan","wufan","zhaozhi","ty__liuqi","zhaoang","huanfan","xizheng","malingli","duanqiaoxiao","ty__ruiji","ty__huaman","xielingyu","dingfuren","quanhuijie","ganfurenmifuren",
"ty_sp__zhenji","fanyufeng","ruanyu","ty__panshu","ty__fengfangnv","caohua","caoxian","liutan","ty__luotong","ty__yangbiao","ruanji","dongguiren","ty__tengfanglan",
"zhangjinyun","zhugejing","ty__chenlin","ty__tengfanglan","ty__tengfanglan"}
--修罗对抗武将
local battleToGens = {"godmachao","godzhangjiao","caofang","ty__liuye","caojinyu","tenggongzhu","guozhao","ty__sunyi","godganning","zerong","zhangfen","ty__sunyi","hulao3__godlvbu","hulao2__godlvbu","zhouyi","godjiangwei","dukui","ty__wangchang"}
--玩家测试武将
local TESTgen = "mouxusheng"
--测试AI武将（避免自由选）
local TESTgens = {"guozhao","m_ex__liaohua","zhangfen","xielingyu","zhouyi","ol__tengfanglan","dongyun","l__zhangliao","ex__simayi","ol_ex__zhangjiao","ty_ex__zhuran","l__lvbu","ty__yanghu","zhaotongzhaoguang","joy__xunyou","miniex__huangyueying","ty__yanghu","joy__xunyou","godzhaoyun","js__guanyu","lvlingqi","dukui","ty_ex__wuyi","ol_ex__sunjian","xizhicai","qinmi","godganning","ty__chenlin","ex__ganning","yuejiu","caomao","ty__lidian","ol__luyusheng","godganning","ty_ex__caozhi","zhaotongzhaoguang"}
--过滤其他卡组（只允许白名单的卡组加入牌堆）
local WHILEcards = {"standard","standard_cards","maneuvering","lang_cards","tenyear_token","mobile_derived","ol_token","overseas_token"}
--保留玩家本模式重要的标记
-- local SAVEmarks = {"curlayerphase","@slash_dmg","@trick_dmg","@pdlbox","@gold_num","@df_lingxin","@shieldnum","@slash_num"}

--初始化游戏对象
-- local initGameObj = function(player)
--   --初始化游戏数据
--   local initGameData = {

--   }
-- end

local xlkj_getLogic = function()
  local xlkj_logic = GameLogic:subclass("xlkj_logic")

  function xlkj_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      { "lord" },
      { "lord", "rebel" },
      { "lord", "rebel", "rebel" },
      { "lord", "rebel", "rebel", "rebel" },
      { "lord", "rebel", "rebel", "rebel", "rebel" },
      { "lord", "loyalist", "loyalist", "loyalist", "rebel", "rebel" },
      { "lord", "rebel", "rebel", "rebel", "rebel", "rebel", "rebel" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "loyalist" },
    }
  end

  function xlkj_logic:prepareForStart()
    local room = self.room
    local players = room.players
    self:addTriggerSkill(GameRule)
    for _, trig in ipairs(Fk.global_trigger) do
      if trig.name ~= "mobile_effect" then  --关闭手杀特效
        self:addTriggerSkill(trig)
      end
    end
    self.room:sendLog{ type = "$GameStart" }
  end

  function xlkj_logic:prepareDrawPile()
    local room = self.room
    --重新过滤卡组
    local filterCardIds = {}
    -- local saveCardIds = {}
    local excepts = {"lightning"} -- 删除一些卡组
    local allCardIds = Fk:getAllCardIds()
    for i = 1, #allCardIds do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived then
          table.insert(room.void, id)
          room:setCardArea(id, Card.Void, nil)
        else
          if table.contains(WHILEcards,card.package.name) then
            if not table.contains(excepts,card.trueName) then
              table.insert(filterCardIds,id)
              -- table.insert(saveCardIds,id)
            end
          end
        end
      end
    end
    table.shuffle(filterCardIds)
    room.draw_pile = filterCardIds
    -- room.totalcards = saveCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
  end

  function xlkj_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    table.shuffle(roles)
    local bots_t = {}
    local players_t = {}
    for i = 1, n do
      local p = room.players[i]
      if p.id < 0 then
        table.insert(bots_t,{p.id,i})
      else
        table.insert(players_t,{p.id,i})
      end
    end
    local randplayer = room.players[table.random(players_t)[2]]
    randplayer.role = "lord"
    randplayer.role_shown = true
    room:broadcastProperty(randplayer, "role")

    local rebles = 4
    for i = 1, n do
      local p = room.players[i]
      if p.role ~= "lord" then
        if p.id < 0 and rebles > 0 then
          p.role = "rebel"
          rebles = rebles - 1
        else
          p.role = "loyalist"
        end
        p.role_shown = true
        room:broadcastProperty(p,"role")
      end
    end
  end

  function xlkj_logic:chooseGenerals()
    local room = self.room
    local lord = room:getLord()
    room.current = lord

    local generalNum = 6
    local generals = table.random(playerGens,30)  --table.random(GensLimts:getDiffStrongGens(2),10)
    local friendgens = table.random(GensLimts:getDiffStrongGens(2),10)

    local command = "MiniGame"
    local game_type = "seeothersel"
    local game = Fk.mini_games[game_type]
    if not game then return end

    local realplayers = {}
    local players = room.players
    local beatenemys = table.random(battleToGens,4)
    for _,pr in ipairs(players) do
      if pr.id > 0 then
        local data = {seat=Fk:translate("seat#"..pr.seat),gens ={},othergens = {},otherseats={}}
        for i = 1,generalNum do
          local gen = table.remove(generals,1)
          table.insert(data.gens,gen)
        end
        if pr.role == "lord" and IStest then
          table.insert(data.gens,"mouxusheng")
        end
        pr.mini_game_data = { type = game_type, data = data }
        table.insert(realplayers,pr)
      else
        if pr.role == "rebel" then
          pr.default_reply = json.encode(table.remove(beatenemys,1))
        else
          pr.default_reply = json.encode(table.remove(friendgens,1))
        end
      end     
    end

    for _,pr in ipairs(realplayers) do
      if pr.id > 0 and pr.mini_game_data then
        if #realplayers == 1 then
          -- table.insert(pr.mini_game_data.data.othergens,pr.mini_game_data.data.gens)
          -- table.insert(pr.mini_game_data.data.othergens,pr.mini_game_data.data.gens)
          -- table.insert(pr.mini_game_data.data.othergens,pr.mini_game_data.data.gens)
          pr.request_data = json.encode(pr.mini_game_data)
          pr.default_reply = game.default_choice and json.encode(game.default_choice(pr, pr.mini_game_data.data)) or ""
        else
          for i, friend in ipairs(realplayers) do
            if pr ~= friend and friend.id > 0 and friend.mini_game_data then
              table.insert(pr.mini_game_data.data.othergens,friend.mini_game_data.data.gens)
              table.insert(pr.mini_game_data.data.otherseats,friend.mini_game_data.data.seat)
            end
          end
          pr.request_data = json.encode(pr.mini_game_data)
          pr.default_reply = game.default_choice and json.encode(game.default_choice(pr, pr.mini_game_data.data)) or ""
        end
      end
    end

    room:notifyMoveFocus(realplayers, "AskForGeneral")
    room:doBroadcastRequest(command, realplayers)

    for _, p in ipairs(players) do
      p.mini_game_data = nil
      if not p.reply_ready then
        p.client_reply = p.default_reply
        p.reply_ready = true
      end
    end

    -- room:askForChooseKingdom(realplayers)
    for _, pr in ipairs(players) do
      if pr.general == "" and pr.reply_ready then
        -- p(pr.client_reply)
        -- dbg()
        local general = json.decode(pr.client_reply)
        room:setPlayerGeneral(pr, general,true)
      else
        room:setPlayerGeneral(pr, "blank_shibing",true)
      end
      -- room:broadcastProperty(pr, "general")
      pr.default_reply = ""
    end
    room:askForChooseKingdom(players)
    for _, p in ipairs(players) do
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "kingdom")
    end
  end
  return xlkj_logic
end

---------------------------------------技能--------------------------------------------
local bingduo = fk.CreateTriggerSkill{
  name = 'bingduoSkill',
  -- anim_type = "negative",
  priority = 10,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill,fk.RoundEnd},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill then
      return player == target and self == data
    else
      return player:hasSkill(self)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      room:drawCards(player, 4,self.name)
    else
      room:handleAddLoseSkills(player,"-"..self.name,nil,false)
    end  
  end,
}
local bingduoMaxMod = fk.CreateMaxCardsSkill{
  name = "#bingduoMaxMod",
  frequency = Skill.Compulsory,
  correct_func = function (self, player)
    if player:hasSkill(self) then
      return -1
    end
  end,
}
bingduo:addRelatedSkill(bingduoMaxMod)
Fk:addSkill(bingduo)
table.insert(getSkillByRoundStart,bingduo.name)
Fk:loadTranslationTable{
  ["bingduoSkill"] = "兵多",
  [":bingduoSkill"] = "锁定技，获得此技能时你摸4张牌，回合内手牌上限-1，每轮结束失去此技能",
  ["#bingduoMaxMod"] = "兵多",
}

local jiangguang = fk.CreateTriggerSkill{
  name = 'jiangguangSkill',
  -- anim_type = "negative",
  priority = 11,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill,fk.AfterSkillEffect,fk.RoundEnd},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill then
      return player == target and self == data
    elseif event == fk.AfterSkillEffect then
      return player == target and player:getMark("skillonce") ~= 0 and table.contains(player:getMark("skillonce"),data.name)
    else
      return player:hasSkill(self)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      local kingdomskills = table.clone(jiangguangSkills[player.kingdom] or jiangguangSkills["qun"])
      local ret = {}
      local n = 4
      while n > 0 and #kingdomskills > 0 do
        local i = math.random(1, #kingdomskills)
        -- local revskill = table.remove(kingdomskills, i)
        if not player:hasSkill(kingdomskills[i]) then
          table.insert(ret,table.remove(kingdomskills, i))
          n = n - 1
        end        
      end
      local chs = room:askForChoices(player,ret,2,2,"#xlkj_rule","#xlkj_rule",false,true)
      room:setPlayerMark(player,"skillonce",chs)
      chs = table.concat(chs,"|")
      room:handleAddLoseSkills(player,chs,nil,false)
    elseif event == fk.AfterSkillEffect then
      local mark = player:getMark("skillonce")
      table.removeOne(mark,data.name)
      room:handleAddLoseSkills(player,"-"..data.name,nil,false)
      if #mark == 0 then
        room:setPlayerMark(player,"skillonce",0)
        room:handleAddLoseSkills(player,"-"..self.name,nil,false)
      else
        room:setPlayerMark(player,"skillonce",mark)
      end
    else
      local mark = player:getMark("skillonce")
      local losestr = "-"..self.name.."|"
      if mark ~= 0 and #mark > 0 then
        for _,ski in ipairs(mark) do
          losestr = losestr.."-"..ski.."|"
        end
      end
      room:handleAddLoseSkills(player,losestr,nil,false)
    end  
  end,
}
Fk:addSkill(jiangguang)
table.insert(getSkillByRoundStart,jiangguang.name)
Fk:loadTranslationTable{
  ["jiangguangSkill"] = "将广",
  [":jiangguangSkill"] = "你可以从4个和你同势力的武将技能选2个技能获得，当因此获得的技能生效后失去该技能。（如果有未触发技能则每轮结束失去这些技能）",
}

local kuangwang = fk.CreateTriggerSkill{
  name = 'kuangwangSkill',
  -- anim_type = "negative",
  priority = 12,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill,fk.RoundEnd,fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill then
      return player == target and self == data
    else
      return player:hasSkill(self)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      player.maxHp = player.maxHp + 3
      player.hp = player.hp + 3
      room:setPlayerProperty(player, "maxHp", player.maxHp)
      room:setPlayerProperty(player, "hp", player.hp)      
    elseif event == fk.RoundEnd then
      room:changeMaxHp(player,-2)
      room:handleAddLoseSkills(player,"-"..self.name,nil,false)
    else
      local judge = {
        who = player,
        reason = "lightning",
        pattern = ".|2~9|spade",
      }
      room:judge(judge)
      if judge.card.suit == Card.Spade and judge.card.number > 1 and judge.card.number < 10 then
        room:damage{
          to = player,
          damage = 3,
          damageType = fk.ThunderDamage,
          skillName = self.name,
        }
      end
    end  
  end,
}
Fk:addSkill(kuangwang)
table.insert(getSkillByRoundStart,kuangwang.name)
Fk:loadTranslationTable{
  ["kuangwangSkill"] = "狂妄",
  [":kuangwangSkill"] = "锁定技，你获得此技能后，体力和体力上限+3。每个回合开始你进行一次闪电判定。每轮结束你失去此技能且体力上限-2",
}

local tri_yongjin = fk.CreateTriggerSkill{
  name = 'tri_yongjinSkill',
  -- anim_type = "negative",
  priority = 13,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and self == data
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local yongjin = Fk.skills["ex__yongjin"]    
    local effect = {from=player.id}
    yongjin.onUse(yongjin, room, effect) 
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(tri_yongjin)
table.insert(getSkillByRoundStart,tri_yongjin.name)
Fk:loadTranslationTable{
  ["tri_yongjinSkill"] = "勇进",
  [":tri_yongjinSkill"] = "你执行十周年界凌统的“勇进”技能效果。",
}

local tri_shenfen = fk.CreateTriggerSkill{
  name = 'tri_shenfenSkill',
  -- anim_type = "negative",
  priority = 14,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and self == data
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = room:getOtherPlayers(player, true)
    room:doIndicate(player.id, table.map(targets, Util.IdMapper))
    table.forEach(targets, function(p)
      if not p.dead then room:damage{ from = player, to = p, damage = 1, skillName = self.name } end
    end)
    table.forEach(targets, function(p)
      if not p.dead then p:throwAllCards("e") end
    end)
    table.forEach(targets, function(p)
      if not p.dead then
        room:askForDiscard(p, 4, 4, false, self.name, false)
      end
    end)
    if not player.dead then player:turnOver() end
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(tri_shenfen)
table.insert(getSkillByRoundStart,tri_shenfen.name)
Fk:loadTranslationTable{
  ["tri_shenfenSkill"] = "神愤",
  [":tri_shenfenSkill"] = "你执行神吕布“神愤”技能效果。",
}

local jingbing = fk.CreateTriggerSkill{
  name = 'jingbingSkill',
  -- anim_type = "negative",
  priority = 15,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and self == data
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local allCardIds = {}
    table.insertTable(allCardIds,room.draw_pile)
    table.insertTable(allCardIds,room.discard_pile)
    for i = 1,2 do
      local cardType = i       
      local allCardMapper = {}
      local allCardNames = {}
      for _, id in ipairs(allCardIds) do
        local card = Fk:getCardById(id)
        if card.type == cardType then
          if allCardMapper[card.name] == nil then
            table.insert(allCardNames, card.name)
          end    
          allCardMapper[card.name] = allCardMapper[card.name] or {}
          table.insert(allCardMapper[card.name], id)
        end
      end  
      if #allCardNames == 0 then return end
      local cardName = room:askForChoice(player, allCardNames, self.name)
      local toGain -- = room:printCard(cardName, Card.Heart, 1)
      if #allCardMapper[cardName] > 0 then
        toGain = allCardMapper[cardName][math.random(1, #allCardMapper[cardName])]
        room:obtainCard(player.id, toGain, true, fk.ReasonPrey)
      end       
    end  
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(jingbing)
table.insert(getSkillByRoundStart,jingbing.name)
Fk:loadTranslationTable{
  ["jingbingSkill"] = "精兵",
  [":jingbingSkill"] = "你可以从牌堆的牌名中分别选择获得【基本牌】、【锦囊牌】各一张。",
}


local qiangjiang = fk.CreateTriggerSkill{
  name = 'qiangjiangSkill',
  -- anim_type = "negative",
  priority = 16,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill,fk.RoundEnd},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill then
      return player == target and self == data
    else
      return player:hasSkill(self)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      local kingdomskills = table.clone(qiangjiangSkills[player.kingdom] or qiangjiangSkills["qun"])
      local ret = {}
      local n = 4
      while n > 0 and #kingdomskills > 0 do
        local i = math.random(1, #kingdomskills)
        -- local revskill = table.remove(kingdomskills, i)
        if not player:hasSkill(kingdomskills[i]) then
          table.insert(ret,table.remove(kingdomskills, i))
          n = n - 1
        end        
      end
      local chs = room:askForChoices(player,ret,1,1,self.name,self.name,false,true)
      chs = chs[1]
      room:setPlayerMark(player,"skillround",chs)
      room:handleAddLoseSkills(player,chs,nil,false)
    else
      local mark = player:getMark("skillround")
      local losestr = "-"..self.name.."|"
      if mark ~= 0 then
        losestr = losestr.."-"..mark.."|"
      end
      room:handleAddLoseSkills(player,losestr,nil,false)
    end  
  end,
}
Fk:addSkill(qiangjiang)
table.insert(getSkillByRoundStart,qiangjiang.name)
Fk:loadTranslationTable{
  ["qiangjiangSkill"] = "强将",
  [":qiangjiangSkill"] = "锁定技，你获得此技能后，从4个和你同势力的武将技能选1个技能获得，每轮结束失去此技能（包含获得的技能）",
}

local shenyu = fk.CreateTriggerSkill{
  name = 'shenyuSkill',
  -- anim_type = "negative",
  priority = 17,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and self == data
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local chc = room:askForChoice(player, {"drawcards3","rechp1","losemaxrec2"}, self.name)
    if chc == "drawcards3" then
      room:drawCards(player, 3,self.name)
    elseif chc == "rechp1" then
      room:recover({
        who = player,
        num = 1,
        skillName = self.name
      })
      room:drawCards(player, 1,self.name)
    else
      room:changeMaxHp(player, -1)
      room:recover({
        who = player,
        num = 2,
        skillName = self.name
      })
    end
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(shenyu)
table.insert(getSkillByRoundStart,shenyu.name)
Fk:loadTranslationTable{
  ["shenyuSkill"] = "神域",
  ["drawcards3"] = "摸3张牌",
  ["rechp1"] = "回复1点体力并摸1张牌",
  ["losemaxrec2"] = "失去1点体力上限并回复2点体力",
  [":shenyuSkill"] = "你从【摸3牌】、【回复1点体力并摸1张牌】、【失去1点体力上限并回复2点体力】3个选项中选1个。",
}

local rongzhuang = fk.CreateTriggerSkill{
  name = 'rongzhuangSkill',
  -- anim_type = "negative",
  priority = 18,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and self == data
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local equipMap = {}
    local allcards = {}
    table.insertTable(allcards,room.draw_pile)
    table.insertTable(allcards,room.discard_pile)
    for _, id in ipairs(allcards) do
      local card = Fk:getCardById(id)
      local sub_type = card.sub_type
      if card.type == Card.TypeEquip and player:hasEmptyEquipSlot(sub_type) then
        local list = equipMap[tostring(sub_type)] or {}
        table.insert(list, id)
        equipMap[tostring(sub_type)] = list
      end
    end

    local put = U.getRandomCards(equipMap, 2)
    if #put > 0 then
      U.moveCardIntoEquip(room, player, put, self.name, true, player)
    end
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(rongzhuang)
table.insert(getSkillByRoundStart,rongzhuang.name)
Fk:loadTranslationTable{
  ["rongzhuangSkill"] = "戎装",
  [":rongzhuangSkill"] = "你从牌堆中随机检索两张不同类别的装备牌置入你的装备区。然后失去此技能。",
}
---------------------------------------技能--------------------------------------------


--修罗抗金模式
local xlkj_rule = fk.CreateTriggerSkill{
  name = "#xlkj_rule",
  priority = 0.001,
  refresh_events = {fk.RoundStart,fk.GameOverJudge,fk.GameStart},
  can_refresh = function(self, event, target, player, data)
    if event == fk.RoundStart then
      return player.role == "lord"
    elseif event == fk.GameOverJudge then
      return player == target
    else
      return player.id < 0
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.RoundStart then
      room:setTag("SkipGameRule", true)
      local players = table.filter(room.alive_players,function(pr) return pr.id > 0 end)
      if #players > 4 then
        room:doBroadcastNotify("ShowToast", "游戏玩家不能超过四人，游戏结束")
        return room:gameOver("rebel")
      end
      for _, p in ipairs(players) do
        local choices = table.random(getSkillByRoundStart,3)
        p.request_data = json.encode({ choices, choices, "#roundchc", "#roundchc", true })      
      end
    
      room:notifyMoveFocus(players, "AskForChoice")
      room:doBroadcastRequest("AskForChoice", players)
      for _, pr in ipairs(players) do
        if pr.reply_ready then
          room:handleAddLoseSkills(pr,pr.client_reply,nil,false)
        end
      end
    elseif event == fk.GameOverJudge then
      local tar = room:getPlayerById(data.who)
      local onlyenemy = table.every(room.alive_players,function(pr) return not GensLimts:isSameCamp(pr,tar) end)
      if not onlyenemy then return end
      local victoryrole = tar.role == "rebel" and "lord" or "rebel"
      room:gameOver(victoryrole)
    else
      local upmaxhp_func = function(pr,v)
        pr.maxHp = pr.maxHp + v
        pr.hp = pr.hp + v
        room:setPlayerProperty(pr, "maxHp", pr.maxHp)
        room:setPlayerProperty(pr, "hp", pr.hp) 
      end
      if player.role == "rebel" then
        upmaxhp_func(player,2)
      else
        upmaxhp_func(player,1)
        room:handleAddLoseSkills(player,"ex__yingzi",nil,false)
      end
    end
  end,
}
Fk:addSkill(xlkj_rule)

local xlkj_mode = fk.CreateGameMode{
  name = "xlkj_mode",
  minPlayer = 8,
  maxPlayer = 8,
  rule = xlkj_rule,
  logic = xlkj_getLogic,
  whitelist = table.clone(WHILEcards),
  winner_getter = function(self, victim)
    local room = victim.room
    local alive = table.filter(room.alive_players, function(p)
      return not p.surrendered
    end)
    if #alive ~= 1 then return "" end
    return alive[1].role
  end,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 10s", passed = playedTime >= 10 } }
    -- if Self.role ~= "lord" then
      table.insert(surrenderJudge, { text = "1v1: left you alive", passed = true})
    -- end
    return surrenderJudge
  end,
}

Fk:addMiniGame{
  name = "seeothersel",
  qml_path = "packages/lang/qml/AllPlayersSelGenBox",
  default_choice = function(player, data)
    return data.gens[1]
  end,
  update_func = function(player, data)
    local room = player.room
    -- p(data)
    -- dbg()
    -- local d = player.mini_game_data.data
    for _,pr in ipairs(room.players) do
      if pr.id > 0 and pr ~= player and pr.mini_game_data then
        -- local friend = pr
        pr:doNotify("UpdateMiniGame", json.encode(data))
      end
    end
  end,
}

Fk:loadTranslationTable{
  ["xlkj_mode"] = "修罗抗金",
  ["#xlkj_rule"] = "修罗抗金",

  ["#roundchc"] = "修罗神礼",

  [":xlkj_mode"] = desc_xlkj_mode,
}

return xlkj_mode
